<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\BaseController;
use app\common\model\content\Category as CategoryModel;
use app\admin\traits\UploadImage;
use app\common\model\content\Article as ArticleModel;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Log;
use app\common\model\content\Category;
use app\common\model\content\Topic as TopicModel;
use app\common\validate\Topic as TopicValidate;

class Topic extends BaseController
{
    //是否关联user模型( 用于权限规则验证 )
    public $relateUser = true;

    use UploadImage;
    //中间件
    protected $middleware = [
        'method:ajax' => ['only'=>['list','save','update','delete','batchDel', 'status','uploadTopicImage']],
    ];

    /**
     * 上传话题图片**
     */
    public function uploadTopicImage(){
        return $this->upload(
            TopicModel::UP_FIELD,
            TopicModel::UP_FOLDER,
            ['width'=>320, 'height'=>320]
            );
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
        return view('topic/index',[
            'category' => Category::getDropList(),
            'urlBase'   => config('filesystem.disks.public.url') . '/',
            'empty_image' => config('app.empty_image')
        ]);
    }


    /**
     * 获取首页列表数据
     */
    public function list(){

        try{
            //获取列表数据
            $data = TopicModel::getListData($this->ruleWhere());


        }catch (\Exception $e){
            //系统错误
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg' => $e->getMessage(),
            ]);
        }

        //成功返回
        return json([
            'code'  => 0,
            'msg'=> '查询列表成功',
            'count' => $data['count'],
            'data'  => $data['list']
        ]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        return view('topic/create',[
            'category' => Category::getDropList()
        ]);
    }

    /**
     * 保存新建的资源
     *
     * @return \think\Response
     */
    public function save()
    {
        return $this->store($this->getModel(TopicModel::class), '创建话题成功.', '创建话题失败.');

    }



    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit(int $id)
    {

        return view('topic/edit',[
            'category' => Category::getDropList(),
            'model'  => $this->getModel(TopicModel::class,$id)
        ]);

    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(int $id)
    {
        return $this->store($this->getModel(TopicModel::class,$id), '修改话题成功.', '修改话题失败.');
    }


    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read(int $id)
    {
        return view('topic/read',[
            'model' => $this->getModel(TopicModel::class,$id,['user'],['articles']),
            'category' => CategoryModel::getDropList(),
            'status' => array(
                ArticleModel::STATUS_PUB => '已发布',
                ArticleModel::STATUS_DRA => '草稿箱',
                ArticleModel::STATUS_TRA => '回收站'
            )
        ]);
    }

    /**
     * 改变话题状态
     */
    public function status(int $id){

        try{
            $status = input('status/s');

            if (!in_array($status, [TopicModel::DONE_NO, TopicModel::DONE_YES]))
                throw new Exception('参数错误.');

            $model = $this->getModel(TopicModel::class,$id);

            if (
                $status == TopicModel::DONE_NO ||
                ($status == TopicModel::DONE_YES && $model->allowDone())
            ){
                $model->status = $status;
                $model->count = ArticleModel::where(['topic_id'=>$id])->count();
                $model->save();
            }

        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
        return json(['code'=>0, 'msg'=>'修改状态成功.']);

    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete(int $id)
    {
        //获取模型
        $model = $this->getModel(TopicModel::class,$id);
        try{
            if ($model->delete() === false){
                throw new Exception('删除话题失败.');
            }

        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        }
        //删除成功
        return json(['code'=>0,'msg'=>'删除话题成功']);
    }

    /**
     * 批量删除
     */
    public function batchDel(){

        try{

            $ids = explode(',', trim(request()->param('ids'),','));

            if($this->batchRule(TopicModel::class, (array) $ids) &&
                TopicModel::destroy($ids) === false )
            {
                throw new Exception('批量删除话题失败.');
            }
        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }

        return json([
            'code' => 0,
            'msg' => '批量删除话题成功.'
        ]);
    }


    /**
     * 处理表单提交
     * @param TopicModel $model
     * @param string $okMsg
     * @param string $errMsg
     * @return \think\response\Json
     */
    private function store(TopicModel $model, string $okMsg, string $errMsg ){
        try{

            //验证数据
            $data = request()->only(['name','desc','category_id','image']);

            validate(TopicValidate::class)->check(array_merge($data, ['id'=>$model->id]));

            if( !$model->save($data) )
                throw new Exception($errMsg);


        } catch (ValidateException $e) {

            //验证错误
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        } catch (\Exception $e){

            //系统错误
            //Log::error($e->getMessage());
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        }

        //添加成功
        return json(['code'=>0,'msg'=>$okMsg]);
    }
}
